package com.spsoft.vatoutinv.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spsoft.core.annotation.AnonymousAccess;
import com.spsoft.core.annotation.Log;
import com.spsoft.core.controller.BaseController;
import com.spsoft.core.enums.LogActionType;
import com.spsoft.core.enums.LogMenuEnum;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BaseException;
import com.spsoft.core.model.Result;
import com.spsoft.core.model.leqidmz.param.BaseNsrRequestParams;
import com.spsoft.core.model.leqidmz.response.QueryEnterpriseInfoVO;
import com.spsoft.einvoicetodmz.service.DmzApiClientService;
import com.spsoft.vatoutinv.entity.vmsfullbswjmanager.VmsFullBswjManager;
import com.spsoft.vatoutinv.entity.vmsmanualinvoice.VmsManualBase;
import com.spsoft.vatoutinv.model.dto.TestDto;
import com.spsoft.vatoutinv.model.dto.vmsfullbswjmanager.VmsFullVswjManagerPageDto;
import com.spsoft.vatoutinv.model.vo.TestVo;
import com.spsoft.vatoutinv.model.vo.vmsfullbswjmanager.VmsFullBswjManagerPageVO;
import com.spsoft.vatoutinv.service.vmsfullbswjmanager.VmsFullBswjManagerService;
import com.spsoft.vatoutinv.service.vmsmanualinvoice.VmsManualBaseService;
import com.spsoft.vms.redis.RedisService;
import com.spsoft.vms.redis.constant.RedisConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Api(tags = {"测试"})
@RequestMapping("/test")
@RequiredArgsConstructor
@Validated
@Slf4j
public class TestController extends BaseController {

    private final RedisService redisService;

    private final DmzApiClientService dmzApiClientService;

    private final VmsFullBswjManagerService fullBswjManagerService;

    private final VmsManualBaseService vmsManualBaseService;

    @ApiOperation("测试接口hellostr")
    @AnonymousAccess(value = "/extInvoiceQuery", method = RequestMethod.POST,permissionCode = "MN_BAS_BUSITYPE")
    @Log(value = "测试案例接口", type = LogActionType.SELECT, menuName = LogMenuEnum.EMPTY)
    public Result<TestVo> hellostr(@RequestBody @Valid TestDto testDto) {
        log.info("hellostr，{}", testDto);
       return Result.OK(new TestVo());
    }

    @ApiOperation("测试redisson锁")
    @AnonymousAccess(value = "/redisson", method = RequestMethod.POST,permissionCode = "")
    @Log(value = "测试redisson锁", type = LogActionType.SELECT, menuName = LogMenuEnum.EMPTY)
    public Result<Object> redisson(@RequestParam("key") String key) {
        String redisLockKey = String.format(RedisConstant.REDIS_FULL_BSWJ_CACHE_KEY, key);
        log.info("测试redisson锁，key：{}", redisLockKey);
        RLock lock = redisService.getLock(redisLockKey);
        boolean success = redisService.tryLock(lock, 3, 500);
        if (!success) {
            log.info("尝试指定次数后均未获取到锁，返回系统繁忙");
            return Result.ERROR(ResponseEnum.REDIS_LOCK_NO_GET);
        }
        log.info("redisson上锁成功，key：{}", redisLockKey);
        try {
            // 得到锁,开始执行业务
            log.info("模拟执行业务，睡眠10s");
            Thread.sleep(10000);
        } catch (Exception e) {
            log.error("出现异常" + e);
            throw new BaseException(e.getMessage());
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                log.info("redisson释放锁成功，key为:{}", redisLockKey);
                lock.unlock();
            } else {
                log.info("redisson释放锁失败，key为:{}", redisLockKey);
            }
        }

        return Result.OK();
    }

    @ApiOperation("测试redis类型")
    @AnonymousAccess(value = "/redisValue", method = RequestMethod.POST,permissionCode = "")
    @Log(value = "测试redis类型", type = LogActionType.SELECT, menuName = LogMenuEnum.EMPTY)
    public Result<Object> redisValue(@RequestParam String deptCode) {

        VmsFullVswjManagerPageDto dto = new VmsFullVswjManagerPageDto();
        dto.setPageNo(1);
        dto.setPageSize(10);
        Result<IPage<VmsFullBswjManagerPageVO>> page = fullBswjManagerService.getPage(dto);
        VmsFullBswjManagerPageVO vmsFullBswjManagerPageVO = page.getData().getRecords().get(0);
        log.info("版式文件信息，{}", JSONObject.toJSONString(vmsFullBswjManagerPageVO));

        String redisKey = String.format(RedisConstant.REDIS_FULL_BSWJ_CACHE_KEY, deptCode);
        redisService.setCacheObject(redisKey, JSONObject.toJSONString(vmsFullBswjManagerPageVO));

        log.info("测试redis类型，deptCode入参，{}", deptCode);
        String value = redisService.getCacheObject(redisKey);
        log.info("redis返回数据1，{}", value);
        log.info("redis返回数据2，{}", JSONObject.toJSONString(value));

        JSONObject jsonObject = JSONObject.parseObject(value);
        String sydwbh = jsonObject.getString("sydwbh");
        log.info("redis返回使用单位，{}", sydwbh);

        VmsFullBswjManager vmsFullBswjManager = JSONObject.parseObject(value, VmsFullBswjManager.class);
        log.info("redis返回数据转换后，{}", JSONObject.toJSONString(vmsFullBswjManager));
        return Result.OK();
    }

    @ApiOperation("添加换行备注")
    @AnonymousAccess(value = "/updateBz", method = RequestMethod.POST,permissionCode = "")
    @Log(value = "添加换行备注", type = LogActionType.SELECT, menuName = LogMenuEnum.EMPTY)
    public Result<Object> updateBz(@RequestParam String id) {
        log.info("添加换行备注，入参id，{}", id);
        // 根据发票id获取发票信息
        LambdaQueryWrapper<VmsManualBase> baseQueryWrapper = new LambdaQueryWrapper<>();
        baseQueryWrapper.eq(VmsManualBase::getId, id);
        VmsManualBase base = vmsManualBaseService.getOne(baseQueryWrapper);
        base.setBz(base.getBz() + "\n" + "测试换行");
        vmsManualBaseService.updateById(base);
        return Result.OK();
    }
}
